import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RequestStatusCode, RequestStatusMessage } from 'src/constants';
import { YixiantongFieldsGoods } from 'src/entities/yixiantong-fields-goods';
import { ReturnResult } from 'src/base/return-result';
import { YixiantongFieldsGoodsService } from 'src/entities/yixiantong-fields-goods-service';
import { YixiantongGoodsListSearchDto } from './yixiantong-goods.dto';

@Injectable()
export class YixiantongGoodsService {
  public constructor(
    @InjectRepository(YixiantongFieldsGoods)
    private readonly yixiantongFieldsGoodsRepository: Repository<YixiantongFieldsGoods>,
    @InjectRepository(YixiantongFieldsGoodsService)
    private yixiantongFieldsGoodsService: Repository<YixiantongFieldsGoodsService>,
  ) {}

  public async getList(searchParams: Partial<YixiantongGoodsListSearchDto>) {
    try {
      const keyword = searchParams.keyword ?? '';
      const page = searchParams.page ?? 1;
      const pageSize = searchParams.pageSize ?? 10;

      let queryBuilder = this.yixiantongFieldsGoodsRepository.createQueryBuilder('goods')
        .skip((page - 1) * pageSize)
        .take(pageSize)
        .where(`goods.status = 1`)
        // .orWhere(`goods.name LIKE %${keyword}%`)
        // .orWhere(`goods.field LIKE %${keyword}%`)
        // .orWhere(`goods.address LIKE %${keyword}%`)
        // .orWhere(`goods.city_name LIKE %${keyword}%`)
        // .limit(100)
        // .getMany();

      if (keyword?.length) {
        queryBuilder = queryBuilder
          .andWhere(`
            goods.name LIKE :keyword
              OR goods.field like :keyword
              OR goods.address like :keyword
              OR goods.cityName like :keyword
          `, { keyword: `%${keyword}%` })
      }
      const list = await queryBuilder
        .select(['goods.id', 'goods.name', 'goods.field', 'goods.address', 'goods.cityName', 'goods.price', 'goods.defaultPrice', 'goods.img', 'goods.createTime', 'goods.updateTime'])
        .orderBy('goods.updateTime', 'DESC')
        .getMany();

      const total = (await this.yixiantongFieldsGoodsRepository.findBy({ status: 1 })).length;

      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.GetListSuccess,
        { list, total }
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        RequestStatusMessage.GetListError,
        null,
        e.message
      );
    }
  }

  public async getDetail(paramId: string) {
    try {
      const id: number = Number(paramId);
      const targetData = await this.yixiantongFieldsGoodsRepository.findOne({
        where: { id, status: 1 },
      });

      if (!targetData?.banners?.length) {
        targetData.setBanners([]);
      }
      const targetDataService = await this.yixiantongFieldsGoodsService.findOne({
        where: { id: targetData.id, status: 1 },
        select: ['parking', 'wifi'],
      });

      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.GetDetailSuccess,
        {
          ...targetData,
          service: targetDataService ?? {},
        }
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        `${RequestStatusMessage.GetDetailError}: ${e.message}`,
        null,
        'Fail'
      );
    }
  }

  public async addListItem(newFormData: YixiantongFieldsGoods) {
    try {
      if (!newFormData.description) {
        newFormData.description = '';
      }
      const targetData = await this.yixiantongFieldsGoodsRepository.save(newFormData);
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.CreateSuccess,
        targetData
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        `${RequestStatusMessage.CreateError}: ${e.message}`,
        null,
        'Fail'
      );
    }
  }

  public async updateListItem(id: string, newFormData: YixiantongFieldsGoods) {
    try {
      const targetData = await this.yixiantongFieldsGoodsRepository.findOne({
        where: { id: Number(id) }
      });
      if (!targetData) {
        throw new Error(RequestStatusMessage.NotFound);
      }
      for (let k in newFormData) {
        if (newFormData[k]) {
          targetData[k] = newFormData[k];
        }
      }
      targetData.updateTime = new Date();
      await this.yixiantongFieldsGoodsRepository.save(targetData);
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.UpdateSuccess,
        targetData
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        `${RequestStatusMessage.UpdateError}: ${e.message}`,
        null,
        'Fail'
      )
    }
  }

  public async deleteListItem(id: string) {
    try {
      const targetData = await this.yixiantongFieldsGoodsRepository.findOne({
        where: { id: Number(id) }
      });
      if (targetData) {
        targetData.status = 0;
        await this.yixiantongFieldsGoodsRepository.save(targetData);
      }
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.DeleteSuccess,
        targetData
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        `${RequestStatusMessage.DeleteError}: ${e.message}`,
        null,
        'Fail'
      );
    }
  }
}
